# API文档地址： https://cloud.baidu.com/doc/OCR/s/zk3h7xz52
from mimetypes import init
from aip import AipOcr

LANS = ['CHN_ENG','ENG','JAP','KOR']
default_options = {
    "language_type": "JAP",
    "detect_direction": "false",    # 是否检测语言方向
    "detect_language": "true",      # 是否检测语言类型
    "paragraph": "false",           # 是否输出段落信息
    "probability": "false"          # 是否返回每段置信度
}

class BaiduOcr:
    options = default_options      
    client = None
    
    def __init__(self, config):
        self.initOptions(config)
        self.initOcr(config)

    def initOcr(self, config):
        self.client = AipOcr(config['BAIDU_OCR_APP_ID'], config['BAIDU_OCR_API_KEY'], config['BAIDU_OCR_SECRET_KEY'])

    def initOptions(self, config):
        t = config['SOURCE_LANGUAGE']
        self.changeSource(t)
        
    def ocrPath(self, path):
        with open(path, 'rb') as f:
            res = self.client.basicGeneral(f.read(), self.options)
            return self.parse(res)

    # 修改识别语言
    def changeSource(self, lan_key):
        if lan_key == 0:
            self.options["detect_language"] = "true"
        else:
            self.options["detect_language"] = "false"
            self.options["language_type"] = LANS[lan_key-1]

    # 解析识别结果
    def parse(self, res):
        word = ''
        if res['words_result']:
            arr = res['words_result']
            for i in range(0, len(arr)):
                word += arr[i]['words']
        return word